package com.apes.fn.scm.crossCompany.transfer.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyTransfer;
import com.apes.fn.scm.crossCompany.transfer.model.CrossCompanyTransferItem;
import com.apes.fn.scm.crossCompany.transfer.repository.CrossCompanyTransferRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.soe.store.database.repository.SceneRepository;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.model.Stock;
import com.apes.scm.account.account.repository.InventoryBatchRepository;
import com.apes.scm.account.account.repository.StockRepository;
import com.apes.scm.account.account.service.InventoryService;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.account.transit.DepositInTransit;
import com.apes.scm.account.transit.DepositInTransitService;
import com.apes.scm.masterdata.frame.service.StoreService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.repository.PurchaseOrderRepository;
import com.apes.scm.stock.transfer.model.Pick;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.crossCompany.transfer.service
 * @ClassName: CrossCompanyTransferService
 * @Author: pyb
 * @CreateTime: 2020-06-19 17:46
 * @Description: 跨公司调拨服务
 * @Version: 1.0
 */
@Service("crossCompanyTransferService")
public class CrossCompanyTransferService extends DomainService {
    CrossCompanyTransferRepository crossCompanyTransferRepository;

    @Autowired
    private void setCrossCompanyTransferRepository(CrossCompanyTransferRepository crossCompanyTransferRepository) {
        this.crossCompanyTransferRepository = crossCompanyTransferRepository;
    }


    ProductAccountService productAccountService;

    @Autowired
    private void setProductAccountService(ProductAccountService productAccountService) {
        this.productAccountService = productAccountService;
    }


    InventoryBatchRepository inventoryBatchRepository;

    @Autowired
    private void setInventoryBatchRepository(InventoryBatchRepository inventoryBatchRepository) {
        this.inventoryBatchRepository = inventoryBatchRepository;
    }

    LocationRepository locationRepository;

    @Autowired
    private void setLocationRepository(LocationRepository locationRepository) {
        this.locationRepository = locationRepository;
    }


    ProductRepository productRepository;

    @Autowired
    private void setProductRepository(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }


    StockRepository stockRepository;

    @Autowired
    private void setStockRepository(StockRepository stockRepository) {
        this.stockRepository = stockRepository;
    }

    StoreService storeService;

    @Autowired
    private void setStoreService(StoreService storeService) {
        this.storeService = storeService;
    }

    @Autowired
    InventoryService inventoryService;

    @Value("${apes.switched:false}")
    private Boolean switched;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    private CrossCompanyTransfer save(SimpleRequest request) {
        if (switched) {
            throw new RuntimeException("跨公司调拨单已被停用，不允许创建；请前往【新跨公司调拨】菜单操作！");
        }
        CrossCompanyTransfer transfer = request.getO(CrossCompanyTransfer.class);
        storeService.judgeFCKBJ(transfer.getReceiptLocation());
        storeService.judgeFCKBJ(transfer.getShipLocation());
        transfer.setState("sent");
        //计算总数
        transfer.setQtyTotal(transfer.getCrossCompanyTransferItems().stream().mapToDouble(CrossCompanyTransferItem::getProductReturnQty).sum());
        //注入场景
        transfer.setScene(SpringManager.getBean(SceneRepository.class).findOne("CT001"));
        transfer.computeAmt();
        transfer = crossCompanyTransferRepository.saveAndFlush(transfer);

        /**未达帐**/
        saveDepositInTransit(transfer);

        //更新库存 批次
        updateProductAvailableAndBatch(transfer, false, "跨公司调拨保存");
        return transfer;
    }

    /**
     * 未达帐
     **/
    private void saveDepositInTransit(CrossCompanyTransfer transfer) {
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        transfer.getCrossCompanyTransferItems().forEach(item -> {
            double occurQty = productAccountService.computeQtyUnit(transfer.getCompany(), item.getProduct(), item.getUom(), item.getProductReturnQty());
            depositInTransitService.save(transfer.getCompany(), transfer.getShipLocation(), transfer.getReceiptLocation().getDepot().getDept(), transfer.getInnerBusinessType(), transfer.getInnerBusinessKey(),
                    item.getId(), item.getProduct(), occurQty, "发货");
            depositInTransitService.save(transfer.getCompany(), transfer.getReceiptLocation(), transfer.getShipLocation().getDepot().getDept(), transfer.getInnerBusinessType(), transfer.getInnerBusinessKey(),
                    item.getId(), item.getProduct(), occurQty, "收货");
        });
    }


    /**
     * 编辑
     *
     * @param request
     * @return
     */
    private CrossCompanyTransfer update(SimpleRequest request) {
        CrossCompanyTransfer transfer = request.getO(CrossCompanyTransfer.class);
        storeService.judgeFCKBJ(transfer.getReceiptLocation());
        storeService.judgeFCKBJ(transfer.getShipLocation());
        transfer.setState("sent");
        transfer.computeAmt();
        //计算总数
        transfer.setQtyTotal(transfer.getCrossCompanyTransferItems().stream().mapToDouble(CrossCompanyTransferItem::getProductReturnQty).sum());
        // 还原库存 批次
        CrossCompanyTransfer companyTransfer = crossCompanyTransferRepository.findOne(transfer.getId());
        updateProductAvailableAndBatch(companyTransfer, true, "跨公司调拨还原");

        /**删除未达帐**/
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        companyTransfer.getCrossCompanyTransferItems().forEach(item -> {
            depositInTransitService.delete(companyTransfer.getInnerBusinessType(), companyTransfer.getInnerBusinessKey(),
                    item.getId(), companyTransfer.getShipLocation());
            depositInTransitService.delete(companyTransfer.getInnerBusinessType(), companyTransfer.getInnerBusinessKey(),
                    item.getId(), companyTransfer.getReceiptLocation());
        });
        transfer = crossCompanyTransferRepository.saveAndFlush(transfer);
        /**未达帐**/
        saveDepositInTransit(transfer);
        //更新库存 批次
        updateProductAvailableAndBatch(transfer, false, "跨公司调拨修改");

        return transfer;
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    private String delete(SimpleRequest request) {
        CrossCompanyTransfer transfer = request.getO(CrossCompanyTransfer.class);
        // 还原库存 批次
        updateProductAvailableAndBatch(crossCompanyTransferRepository.findOne(transfer.getId()), true, "跨公司调拨还原");

        /**删除未达帐**/
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        transfer.getCrossCompanyTransferItems().forEach(item -> {
            depositInTransitService.delete(transfer.getInnerBusinessType(), transfer.getInnerBusinessKey(),
                    item.getId(), transfer.getShipLocation());
            depositInTransitService.delete(transfer.getInnerBusinessType(), transfer.getInnerBusinessKey(),
                    item.getId(), transfer.getReceiptLocation());
        });

        crossCompanyTransferRepository.delete(transfer.getId());
        return "删除成功";
    }

    /**
     * 申请
     *
     * @param request
     * @return
     */
    private CrossCompanyTransfer apply(SimpleRequest request) {
        CrossCompanyTransfer transfer = request.getO(CrossCompanyTransfer.class);
        transfer.setState("apply");
        //计算总数
        transfer.setQtyTotal(transfer.getCrossCompanyTransferItems().stream().mapToDouble(CrossCompanyTransferItem::getProductReturnQty).sum());
        transfer.setApplyUid(this.getPerson(request));
        transfer.setDateApply(new Date());
        transfer = crossCompanyTransferRepository.saveAndFlush(transfer);
        return transfer;
    }

    /**
     * 驳回申请
     *
     * @param request
     * @return
     */
    private CrossCompanyTransfer reject(SimpleRequest request) {
        CrossCompanyTransfer transfer = request.getO(CrossCompanyTransfer.class);
        transfer.setState("reject");
        transfer.setApproveUid(this.getPerson(request));
        transfer.setDateApprove(new Date());
        transfer = crossCompanyTransferRepository.saveAndFlush(transfer);
        // 还原库存 批次
        updateProductAvailableAndBatch(crossCompanyTransferRepository.findOne(transfer.getId()), true, "跨公司调拨还原");
        /**删除未达帐**/
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        CrossCompanyTransfer finalTransfer = transfer;
        transfer.getCrossCompanyTransferItems().forEach(item -> depositInTransitService.delete(finalTransfer.getInnerBusinessType(), finalTransfer.getInnerBusinessKey(),
                item.getId(), finalTransfer.getReceiptLocation()));
        return transfer;
    }

    /**
     * 审核
     *
     * @param request
     * @return
     */
    private CrossCompanyTransfer approve(SimpleRequest request) {
        CrossCompanyTransfer transfer = request.getO(CrossCompanyTransfer.class);
        transfer.setState("approve");
        //计算总数
        transfer.setQtyTotal(transfer.getCrossCompanyTransferItems().stream().mapToDouble(CrossCompanyTransferItem::getProductReturnQty).sum());
        transfer.setApproveUid(this.getPerson(request));
        transfer.setDateApprove(new Date());
        transfer = crossCompanyTransferRepository.saveAndFlush(transfer);
        return transfer;
    }

    /**
     * 处理交货动作
     *
     * @param request
     * @return
     */
    private CrossCompanyTransfer ship(SimpleRequest request) {
        Pick pick = request.getO(Pick.class);
        CrossCompanyTransfer companyTransfer = crossCompanyTransferRepository.findOne(pick.getOrigin());
        companyTransfer.setCreator(pick.getDoneUid().getId());
        Optional.ofNullable(companyTransfer).orElseThrow(() -> new RuntimeException("无法找到跨公司调拨单,交货单号:" + pick.getId()));
        companyTransfer.setState("ship");
        return crossCompanyTransferRepository.saveAndFlush(companyTransfer);
    }

    /**
     * 更新商品库存可用数，批次表冻结数量
     *
     * @param crossCompanyTransfer
     * @param flag
     * @param note
     */
    private void updateProductAvailableAndBatch(CrossCompanyTransfer crossCompanyTransfer, boolean flag, String note) {
        crossCompanyTransfer.getCrossCompanyTransferItems().forEach(item -> {
            //退货数量
            double changeQty = Math.abs(item.getProductReturnQty());
            if (!flag) {
                changeQty = -1 * changeQty;
            }
            if (LogicalUtil.notIn(item.getProduct().getType(), "aut")) {
                // 减少（增加）商品可用数
                productAccountService.setProductAvailable(item.getProduct(), crossCompanyTransfer.getShipLocation(),
                        item.getUom(), changeQty, crossCompanyTransfer.getInnerBusinessType(), crossCompanyTransfer.getId(),
                        String.valueOf(item.getId()), note, crossCompanyTransfer.getCompany());
            }


            // 增加（减少）商品价值（商品批次） 的冻结数量
            // 查询批次信息
            InventoryBatch inventoryBatch = inventoryBatchRepository.findOne(item.getInventoryBatch().getId());
            inventoryService.changeFrostQty(inventoryBatch, item.getUom(), -1 * changeQty, crossCompanyTransfer.getCompany(), crossCompanyTransfer.getInnerBusinessType(), crossCompanyTransfer.getId(),
                    String.valueOf(item.getId()), note);
        });
    }

    /**
     * 查找可调拨批次
     *
     * @param request
     * @return
     */
    public Map findInventory(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        String productId = requestJO.getString("productId");
        String locationId = requestJO.getString("locationId");
        String companyId = requestJO.getString("companyId");
//
//        //批次上的供应商为该退货基地
//        String receiptLocationId = requestJO.getString("receiptLocation");
//        Location receiptLocation = locationRepository.findOne(receiptLocationId);

        //判断工时商品
        Product product = productRepository.findOne(productId);
        if (LogicalUtil.in(product.getType(), "aut")) {
            throw new RuntimeException("服务商品不支持跨公司调拨");
        }
        // 查找商品库存帐的可用数是否大于0
        Stock stock = stockRepository.findFirstByProductIdAndLocationIdAndUsableQtyGreaterThan(productId, locationId, 0);
        // 获取可用数
        double usableQty = Optional.ofNullable(stock).map(Stock::getUsableQty).orElseThrow(() -> new RuntimeException("该商品无可用库存!"));

        // 获取结存大于冻结的批次\
        Page<InventoryBatch> inventoryBatchPage ;
        if (!requestJO.getBoolean("isNew")){
            //供应商固定A001
            String supplierId = "A1001";
            inventoryBatchPage = inventoryBatchRepository.findReturnableByCompanyIdAndProductIdAndSupplier(companyId, productId, supplierId, PageRequest.of(request.get("page"), request.get("size")));

        } else {
            Location shipLocation = locationRepository.findOne(locationId);
            if (!shipLocation.getCompany().getParty().getCorporate().getOperation().getDescription().equals("直营")){
                //供应商固定A001
                String supplierId = "A1001";
                inventoryBatchPage = inventoryBatchRepository.findReturnableByCompanyIdAndProductIdAndSupplier(companyId, productId, supplierId, PageRequest.of(request.get("page"), request.get("size")));
            } else {
                inventoryBatchPage = inventoryBatchRepository.findReturnableByCompanyIdAndProductIdNotInSupplierId(companyId, productId, PageRequest.of(request.get("page"), request.get("size")));
            }

        }
        inventoryBatchPage.getContent().forEach(
                (inventoryBatch) -> {
                    inventoryBatch.setUsableQty(usableQty);
                    inventoryBatch.setCanReturnQty(Math.min(usableQty, inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty()));
                    inventoryBatch.setFactor(1/inventoryBatch.getUom().getFactor());
                }
        );
        Map mapper = MapUtil.mapped(inventoryBatchPage);
        if (inventoryBatchPage.getContent().size() == 0) {
            mapper.put("msg", "未找到集群车宝(A1001)供货的数据！");
        }
        return mapper;

    }

    /**
     * 功能：处理采购收货完成事件
     */
    @Listener(topic = "event:stock.pick.delivery")
    public void delivery(SimpleRequest request) {
        JSONObject param = request.getJO();
        if (!param.getString("originBusinessType").equals(PurchaseOrder.class.getSimpleName())) return;
        PurchaseOrder purchaseOrder = SpringManager.getBean(PurchaseOrderRepository.class).findOne(param.getString("origin"));
        if (purchaseOrder.getOriginBusinessType() == null) return;
        if (!"CrossCompanyTransfer".equals(purchaseOrder.getOriginBusinessType())) return;
        if ("receipt".equals(param.getString("operation"))) {
            CrossCompanyTransfer transfer = crossCompanyTransferRepository.findOne(purchaseOrder.getOrigin());
            Optional.ofNullable(transfer).orElseThrow(() -> new RuntimeException(String.format("根据采购订单原始单据[%s]无法追溯到跨公司调拨单！", purchaseOrder.getOrigin())));
            double qtyDoneSum = param.getJSONArray("items").stream().mapToDouble((item) -> ((JSONObject) item).getDouble("qtyDone")).sum();
            // 更新交货状态以及单据状态
            transfer.delivery(qtyDoneSum);
            transfer.setCrossSystem("esb");
            if (transfer.getQtyTotal() == transfer.getQtyReceived()) {
                transfer.setState("receipt");
            }
            // 用于判断是否触发场景流
            if ("receipt".equals(transfer.getState())) {
                transfer = crossCompanyTransferRepository.saveAndFlush(transfer);

                /**删除未达帐**/
                DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
                CrossCompanyTransfer finalTransfer = transfer;
                transfer.getCrossCompanyTransferItems().forEach(item -> depositInTransitService.delete(finalTransfer.getInnerBusinessType(), finalTransfer.getInnerBusinessKey(),
                        item.getId(), finalTransfer.getReceiptLocation()));

            } else {
                crossCompanyTransferRepository.save(transfer);
            }

        }

    }

    /**
     * 批量导入调拨明细
     *
     * @param request
     * @return
     */
    public JSONObject beImport(SimpleRequest request) {
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray field = (JSONArray) request.get("data");
        JSONObject exclObject = new JSONObject();                  //返回值

        JSONArray exclArr = new JSONArray();            //行内容
        JSONArray headerName = new JSONArray();         //头部
        JSONArray fieldName = new JSONArray();          //field
        for (Object o : field) {
            JSONObject webTab = (JSONObject) o;
            headerName.add(webTab.get("name"));
            fieldName.add(webTab.get("field"));
        }
        //获取model
        JSONObject model = request.get("model");
        String companyId = model.getJSONObject("company").getString("id");
        String supplierId = "A1001";
        String locationId = model.getJSONObject("shipLocation").getString("id");

        //业务逻辑
        importData.forEach((k, v) -> {
            //获得value ===Excel内容
            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //首行数据
            String productId;
            for (int i = 0; i < excl.size(); i++) {  //遍历每一行

                if (i == 0) { //跳过首行
                    exclArr.add(headerName);
                    continue;
                }

                JSONArray lineLong = (JSONArray) excl.get(i); //当前行
                if (lineLong.size() == 0) {
                    continue; //跳过空白行
                }
                //合并2个list为一个map,KEY为首行数据，Value为当前行数据
                Map<String, String> rst = IntStream.range(0, header.size()).collect(HashMap::new,
                        (m, key) -> m.put(header.getString(key).replace(";", ""),
                                key >= lineLong.size() ? "" : (lineLong.getString(key) == null ? null : lineLong.getString(key).trim().replaceAll("[\\s]{2,}", " "))),
                        (m1, m2) -> {
                        });
                productId = rst.get("商品");
                double qty = Double.parseDouble(rst.get("调拨数量"));
                if (qty <= 0) {
                    throw new RuntimeException(String.format("商品[%s]调拨数量小于等于0，请检查调拨文件！",productId));
                }
                Product product = SpringManager.getBean(ProductRepository.class).findOne(productId);
                Optional.ofNullable(product).orElseThrow(() -> new RuntimeException(String.format("商品[%s]不存在", rst.get("商品"))));

                List<Stock> stocks = stockRepository.findByLocationAndProduct(locationId, productId);
                double usableQty = stocks.stream().mapToDouble(Stock::getUsableQty).sum();
                if (stocks.isEmpty() || usableQty < qty) {
                    throw new RuntimeException(String.format("仓库[%s]商品[%s]库存不够，请检查库存帐！", locationId, productId));
                }

                //获取批次
                List<InventoryBatch> inventoryBatches = inventoryBatchRepository.findReturnableByCompanyIdAndProductIdAndSupplier(companyId, product.getId(), supplierId);
                double canReturnQtySum = inventoryBatches.stream().mapToDouble(mx -> mx.getBalanceQty() - mx.getFrostQty()).sum();
                if (inventoryBatches.isEmpty() || canReturnQtySum < qty) {
                    throw new RuntimeException(String.format("公司[%s]商品[%s][%s]批次可调拨数不够，请检查批次帐！", companyId, productId,product.getName()));
                }
                //获取数量足够的批次
                double finalQty = qty;
                List<InventoryBatch> batches = inventoryBatches.stream().filter(inventoryBatch -> (inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty()) >= finalQty).collect(Collectors.toList());
                if (batches.isEmpty()) {
                    for (InventoryBatch inventoryBatch : inventoryBatches) {
                        //计算税金
                        Map compute = inventoryBatch.getTax().computeAll(inventoryBatch.getCompany(), inventoryBatch.getTaxCostPrice(), inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty());
                        //用一个有序的map 封装数据, 防止乱序
                        double canReturnQty = inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty();
                        Map<String, Object> map = new LinkedHashMap<>();
                        map.put("序号", "");
                        map.put("供应商", inventoryBatch.getSupplier());
                        map.put("商品", product);
                        map.put("库存可用数", usableQty);
                        map.put("批次内码", inventoryBatch);
                        map.put("批次可调拨数量", inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty());
                        map.put("调拨数量", Math.min(qty, canReturnQty));
                        map.put("单价", inventoryBatch.getTaxCostPrice());
                        map.put("单位", inventoryBatch.getUom());
                        map.put("税率", inventoryBatch.getTax());
                        map.put("金额", compute.get("totalIncluded"));
                        //将map 转换成 list 利用stream流 引用Map类的getValue方法,弄成一个list
                        List<Object> valueList = new ArrayList<>(map.values());
                        exclArr.add(valueList);
                        qty = qty - canReturnQty;
                        if (qty <= 0) {
                            break;
                        }
                    }
                } else {
                    InventoryBatch inventoryBatch = batches.stream().findFirst().get();
                    //计算税金
                    Map compute = inventoryBatch.getTax().computeAll(inventoryBatch.getCompany(), inventoryBatch.getTaxCostPrice(), qty);
                    //用一个有序的map 封装数据, 防止乱序
                    Map<String, Object> map = new LinkedHashMap<>();
                    map.put("序号", "");
                    map.put("供应商", inventoryBatch.getSupplier());
                    map.put("商品", product);
                    map.put("库存可用数", usableQty);
                    map.put("批次内码", inventoryBatch);
                    map.put("批次可调拨数量", inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty());
                    map.put("调拨数量", qty);
                    map.put("单价", inventoryBatch.getTaxCostPrice());
                    map.put("单位", inventoryBatch.getUom());
                    map.put("税率", inventoryBatch.getTax());
                    map.put("金额", compute.get("totalIncluded"));
                    //将map 转换成 list 利用stream流 引用Map类的getValue方法,弄成一个list
                    List<Object> valueList = new ArrayList<>(map.values());
                    exclArr.add(valueList);
                }
            }
            exclObject.put(k, exclArr);
        });


        return exclObject;
    }

    /**
     * 处理已发货未收货单据（调帐专用）（慎用）
     **/
    public void reconciliation(SimpleRequest request) {
        String id = request.get("id");
        CrossCompanyTransfer transfer = crossCompanyTransferRepository.findOne(id);
        if (transfer == null) throw new RuntimeException("调拨单：" + id + " 在系统中不存在！");
        if (!"ship".equals(transfer.getState())) throw new RuntimeException("只处理已发货未收货单据！");
        String note = "跨公司调拨还原[调帐]";
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        transfer.getCrossCompanyTransferItems().stream().forEach(item -> {
            double changeQty = Math.abs(item.getProductReturnQty());
            if (LogicalUtil.notIn(item.getProduct().getType(), "aut")) {
                //还原可用数（含明细账）
                productAccountService.setProductAvailable(item.getProduct(), transfer.getShipLocation(),
                        item.getUom(), changeQty, transfer.getInnerBusinessType(), transfer.getId(),
                        String.valueOf(item.getId()), note, transfer.getCompany());
                //还原保管数（含明细账）
                productAccountService.setProductCustody(item.getProduct(), transfer.getShipLocation(),
                        item.getUom(), changeQty, transfer.getInnerBusinessType(), transfer.getId(),
                        String.valueOf(item.getId()), note, transfer.getCompany());

            }

            // 还原批次冻结数（含明细账）
            InventoryBatch inventoryBatch = inventoryBatchRepository.findOne(item.getInventoryBatch().getId());
            inventoryService.changeFrostQty(inventoryBatch, item.getUom(), -1 * changeQty, transfer.getCompany(), transfer.getInnerBusinessType(), transfer.getId(),
                    String.valueOf(item.getId()), note);

            /**删除未达帐**/
            depositInTransitService.delete(transfer.getInnerBusinessType(), transfer.getInnerBusinessKey(),
                    item.getId(), transfer.getShipLocation());
            depositInTransitService.delete(transfer.getInnerBusinessType(), transfer.getInnerBusinessKey(),
                    item.getId(), transfer.getReceiptLocation());
        });

        //更新调拨单状态
        transfer.setState("reject");
        crossCompanyTransferRepository.save(transfer);
    }

    private Boolean getSwitchedValue(SimpleRequest request) {
        return switched;
    }
}
